import Web3 from 'web3';
import { promises as fs } from 'fs';

const jsonData = await fs.readFile('./build/contracts/AdventureLayerTransfer.json', 'utf-8');
const bridgeJson = JSON.parse(jsonData);
const bridgeAbi = bridgeJson.abi;
//console.log(bridgeAbi);

// 配置参数
// account7
 const USER_ADDRESS = '0x4C59A2AA9F39554b9f8D474d70AA3A7cB2467771'; // 你的钱包地址
 const PRIVATE_KEY = '0x7196e384031bb4f6e3647ee2166c574c758e44c4c79907d23ac5a602a96f3340'; // 你的钱包私钥


const RPC_URL = 'http://[::1]:8545'; // 你的以太坊节点RPC URL
const BRIDGE_CONTRACT_ADDRESS = '0xFAC84eB36101CCB7ce39e841BB82E82a236f2C9d'; // L1Bridge 合约地址


const TOKEN_CONTRACT_ADDRESS = '0x43F0FFCA27B26dCfA02fce8cA5D97F2F85CbF3fa'; // ERC20 代币合约地址

// Web3 设置
const web3 = new Web3(RPC_URL);

// 后续的 Web3 合约和交易操作
console.log('Web3 已成功连接:', web3.currentProvider.host);

// 代币 ABI 和 L1Bridge 合约 ABI
// const bridgeAbi = [
//     { "constant": false, "inputs": [{ "name": "amount", "type": "uint256" }], "name": "deposit", "outputs": [], "type": "function" },
//     { "anonymous": false, "inputs": [{ "indexed": true, "name": "user", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "timestamp", "type": "uint256" }], "name": "Deposit", "type": "event" }
// ];

const erc20Abi = [
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }, { "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" }
];

async function main() {
    try {
        // 创建钱包签名者
        const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
        web3.eth.accounts.wallet.add(account);
        web3.eth.defaultAccount = account.address;

        // 创建 L1Bridge 合约实例
        const bridgeContract = new web3.eth.Contract(bridgeAbi, BRIDGE_CONTRACT_ADDRESS);

        console.log("开始监听 Deposit 事件...");
        
        // 监听 Deposit 事件
        bridgeContract.events.Deposit({
            filter: { user: USER_ADDRESS },
            fromBlock: 'latest'
        })
        .on('data', (event) => {
            console.log("检测到存款事件:");
            console.log(`用户地址: ${event.returnValues.user}`);
            console.log(`存款金额: ${web3.utils.fromWei(event.returnValues.amount, 'ether')} Tokens`);
            console.log(`时间戳: ${new Date(Number(event.returnValues.timestamp) * 1000).toLocaleString()}`);
            console.log('-----------------------------');
        })
        .on('error', (error) => {
            //console.error("事件监听发生错误:", error);
            // 重新启动监听
            main().catch(console.error);
        });

        // 保持程序运行
        process.stdin.resume();

        // 优雅地处理进程退出
        process.on('SIGINT', () => {
            console.log('正在停止监听...');
            process.exit();
        });

    } catch (error) {
        //console.error("发生错误:", error);
        // 延迟 5 秒后重试
        setTimeout(() => {
            main().catch(console.error);
        }, 5000);
    }
}

// 启动主程序
main().catch(error => {
    console.error("主程序发生错误:", error);
    // 延迟 5 秒后重试
    setTimeout(() => {
        main().catch(console.error);
    }, 5000);
});
